package com.dc.common.aop;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.dc.common.model.BaseModel;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.dc.base.exception.BusinessException;
import com.dc.common.constants.ConstantsCommon;

@Component
@Aspect
public class ResubmitAspect {

	// 日志记录对象
	private static final Logger logger = LoggerFactory.getLogger(ResubmitAspect.class);

	@Pointcut("@annotation(com.dc.common.aop.ResubmitAop)")
	public void resubmitAspect() {
	}

	@Before("resubmitAspect() && @annotation(data)")
	public void doBefore(JoinPoint point, ResubmitAop data) throws Throwable {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		// 判断session和请求传过来的token令牌是否一致
		// 获取session中的token
		String token_fromSession = (String) session.getAttribute(ConstantsCommon.TOKEN);
		// 获取baseModel
		BaseModel baseModel = new BaseModel();
		if (point.getArgs() != null) {
			for (Object obj : point.getArgs()) {
				if (obj.getClass() == BaseModel.class) {
					baseModel = (BaseModel) obj;
					break;
				}
			}
		}
		// 获取请求参数中的token
		String token_fromBaseModel = baseModel.getToken();
		if(token_fromBaseModel==null||"".equals(token_fromBaseModel)){
			throw new BusinessException(-101,"新增操作令牌获取失败!");
		}
		// 比较token
		// token一致的情况下清除session中的token,token不一致的情况下返回错误信息

		if(token_fromSession!=null&&!"".equals(token_fromSession) && token_fromSession.equals(token_fromBaseModel)) {
			session.setAttribute(ConstantsCommon.TOKEN, null);
		}else{
			throw new BusinessException(7,"请不要重复提交!");
		}
	}

}
